package data_structures_and_algorithms.tree;

import common.TreeNode;

import java.util.*;

public class Code_0103_zigzagLevelOrder {


    public static void main(String[] args) {
        TreeNode treeNode3 = new TreeNode(3);
        TreeNode treeNode9 = new TreeNode(9);
        TreeNode treeNode20 = new TreeNode(20);
        TreeNode treeNode15 = new TreeNode(15);
        TreeNode treeNode7 = new TreeNode(7);
        treeNode3.left = treeNode9;
        treeNode3.right = treeNode20;
        treeNode20.left = treeNode15;
        treeNode20.right = treeNode7;

        List<List<Integer>> lists = new Code_0103_zigzagLevelOrder().zigzagLevelOrder(treeNode3);
        System.out.println("---");


    }

    public List<List<Integer>> zigzagLevelOrder(TreeNode root) {
        if (root == null)
            return new ArrayList<>();
        Deque<TreeNode> deque = new LinkedList<>();
        deque.addLast(root);
        List<List<Integer>> ans = new LinkedList<>();
        boolean isFromLeft  = true;
        while (!deque.isEmpty()){
            int size = deque.size();
            List<Integer> list = new LinkedList<>();
            for (int i = 0; i < size; i++) {
                TreeNode treeNode = deque.removeFirst();
                list.add(treeNode.val);
                if (treeNode.left != null){
                    deque.addLast(treeNode.left);
                }
                if (treeNode.right != null){
                    deque.addLast(treeNode.right);
                }
            }
            if (!isFromLeft){
                Collections.reverse(list);
            }
            isFromLeft = !isFromLeft;
            ans.add(list);
        }
        return ans;
    }
}
